package com.san.oms.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.san.base.domain.Tree;
import com.san.common.annotation.Log;
import com.san.common.config.Constant;
import com.san.common.utils.R;
import com.san.oms.domain.ModelRoleDO;
import com.san.oms.domain.ModelScDTO;
import com.san.oms.service.ModelRoleService;
import com.san.system.domain.DeptDO;
import com.san.system.service.DeptService;

@RequestMapping("/ce/modelRole")
@Controller
public class ModelRoleController {

	private static final Logger logger = LoggerFactory.getLogger(ModelRoleController.class);

	private String PREFIX = "ce/modelrole";
	
	@Autowired
	private DeptService deptService;
	
	@Autowired
	private ModelRoleService modelRoleService;
	
	@RequiresPermissions("ce:role:view")
	@GetMapping()
	String role() {
		return PREFIX + "/view";
	}
	
	@Log("编辑部门权限")
	@RequiresPermissions("ce:role:edit")
	@GetMapping("/edit/{id}")
	String edit(@PathVariable("id") Long id, Model model) {
		try {
			DeptDO dept = (DeptDO) deptService.getById(id);
			model.addAttribute("dept", dept);
			
			if (Constant.DEPT_ROOT_ID.equals(dept.getParentId())) {
				model.addAttribute("parentDeptName", "无");
			} else {
				DeptDO parDept = (DeptDO) deptService.getById(dept.getParentId());
				model.addAttribute("parentDeptName", parDept.getName());
			}
			
		} catch (Exception e) {
			logger.error("获取部门失败", e);
		}
		return PREFIX + "/edit";
	}
	
	@Log("更新部门权限")
	@RequiresPermissions("ce:role:edit")
	@PostMapping("/doEdit")
	@ResponseBody()
	R doEdit(ModelRoleDO modelRoleDO) {
		try {
			modelRoleService.doEdit(modelRoleDO);
				return R.ok();
		} catch (Exception e) {
			logger.error("更新部门权限", e);
		}

		return R.error(1, "更新失败");
	}
	
	/**
	 * 
	 * @param deptId
	 * @return
	 */
	@GetMapping("/tree/{deptId}")
	@ResponseBody
	Tree<ModelScDTO> tree(@PathVariable("deptId") Long deptId) {
		Tree<ModelScDTO> tree = null;
		try {
			tree = modelRoleService.getTree(deptId);
		} catch (Exception e) {
			logger.error("获取权限树失败", e);
		}
		return tree;
	}
	
}
